package Week1.J0418;

// 1. for循环中变量名混淆 排查bug花了很长时间
// 2. 忘记设置vis数组来表示已查找，设置后忘记复原vis[x][y];

public class WordSearch_xv {
    int m;
    int n;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    boolean[][] vis;
    char[] wordCh;

    public boolean exist(String[] board, String word) {

        m = board.length;
        n = board[0].length();
        wordCh = word.toCharArray();
        vis = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i].charAt(j) == wordCh[0]) {
                    if (dfs(board, i, j, 0)) return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(String[] board, int i, int j, int pos) {
        if (pos == wordCh.length - 1) return true;

        vis[i][j] = true;

        for (int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && board[x].charAt(y) == wordCh[pos + 1]) {
                if (dfs(board, x, y, pos + 1)) return true;
            }
        }

        vis[i][j] = false;

        return false;
    }
}
